// pages/remind/remind.js
const api = require('../../util')
const regeneratorRuntime = require('../../runtime')
Page({

    /**
     * 页面的初始数据
     */
    data: {
        title: -1, // 底部按钮类型
        options: {},
        reminder_id: '', // 用户编辑id
        btmh: 0, // 底部的高度
        active: null, // 药品名称选中的index
        activeid: null, // 药品名称选中的id
        scid: '', // scroll-view滚动位置
        showscid: true, // 是否展示滚动scroll
        showscidname: '',// 是展示滚动scroll时的药品名称
        select: false, // 选择遮罩
        arr: [],
        commonlyUsedDrugs: [], // 常用药品
        sousuolist: [], // 搜索列表
        frequencyarr: [{title: '每日'},{title: '每周'},{title: '每月'}],
        numberarr: [{title: '1次',id:'1'},{title: '2次',id:'2'},{title: '3次',id:'3'},{title: '4次',id:'4'},{title: '5次',id:'5'},{title: '6次',id:'6'}],
        dosagearr: [],
        zlist: [{title:'周一',type: false},{title:'周二',type: false},{title:'周三',type: false},{title:'周四',type: false},{title:'周五',type: false},{title:'周六',type: false},{title:'周日',type: false}],
        ylist:[], // 月数组
        json: [], // 拷贝月数组
        type: [], // 药品类别
        rtype: [],
        showbtm: false, // 是否展示底部提示
        plactive: 0, // 遮罩选中的类型
        showall: true, // 显示全部类型
        inpval: '',
        oldval: '',
        // 页面显示的下拉文本
        obj: {
            data: '', // 开始时间
            days: '', // 天数
            frequency: '', // 频率
            number: '', // 次数
            dosage: '' // 每次用量
        },
        plactiveid: 0, // 药品id
        // 选中的下标
        daysindex: 0, // 用药天数
        frequencyindex: 0, // 用药频率
        numberindex: 0, // 用药次数
        dosageindex: [0, 0], // 每次用量选中
        time: [], // 用药时间
    },
    before() {
        wx.navigateBack({
          delta: 1
        })
    },
    // 获取用药详情（编辑回显）
    reminderDetails() {
        var that = this
        return new Promise((resolve,reject)=> {
            api.http('/MedicationReminder/reminderDetails', 'POST', true, {
                reminder_id: this.data.options.reminder_id
            }, function (res) {
                if(res.code == 200) {
                    // 药品分类
                    that.data.plactiveid = res.data.category_id
                    // 药品名
                    for (let i = 0; i < that.data.commonlyUsedDrugs.length; i++) { // 滚动距离及下标
                        if (that.data.commonlyUsedDrugs[i].id == res.data.drugs_id) {
                            that.setData({
                                scid: "scid"+res.data.drugs_id,
                                showscidname: '',
                                active: i,
                                showscid: true,
                                activeid: res.data.drugs_id
                            })
                        }
                    }
                    if (that.data.active == null) {
                        that.setData({
                            scid: '',
                            showscidname: res.data.drugs_name,
                            showscid: false,
                            activeid: res.data.drugs_id
                        })
                    }
                    // 开始时间
                    that.setData({
                        'obj.data':  res.data.start_date
                    })
                    // 用药天数
                    for (let j = 0; j < that.data.arr.length; j++) {
                        if (that.data.arr[j].id == res.data.day_id) {
                            that.setData({
                                daysindex: j,
                                'obj.days':  that.data.arr[j].title
                            })
                        }
                    }
                    // 用药频率
                    var zlists = res.data.days.split(',')
                    if (res.data.company == 'day') {
                        that.setData({
                            frequencyindex: 0,
                            'obj.frequency': '每日'
                        })
                    } else if (res.data.company == 'week') {
                        that.setData({
                            frequencyindex: 1,
                            'obj.frequency': '每周'
                        }, () => {
                            for (let z = 0; z < that.data.zlist.length; z++) {
                                for (let p = 0; p < zlists.length; p++) {
                                    if (z+1 == zlists[p]) {
                                        that.data.zlist[z].type = true
                                    }
                                }
                            }
                            that.setData({
                                zlist: that.data.zlist
                            })
                        })
                    } else if (res.data.company == 'month') {
                        that.setData({
                            frequencyindex: 2,
                            'obj.frequency': '每月'
                        }, () => {
                            for (let z = 0; z < that.data.ylist.length; z++) {
                                for (let p = 0; p < zlists.length; p++) {
                                    if (z+1 == zlists[p]) {
                                        that.data.ylist[z].type = true
                                    }
                                }
                            }
                            that.setData({
                                ylist: that.data.ylist
                            })
                        })
                    }
                    // 每次用量&用药时间
                    var usage_time = res.data.usage_time.split(',')
                    that.setData({
                        'obj.dosage': res.data.consumption,
                        time: usage_time,
                        numberindex: usage_time.length,
                        'obj.number': that.data.numberarr[usage_time.length-1].title,
                         reminder_id: res.data.id
                    })
                }
                // 监听回显数据获取底部文字显示隐藏
                that.watchstr()
                wx.hideLoading();
                resolve(true)
            })
        })
    },
    // 获取常用药品
    commonlyUsedDrugs() {
        var that = this
        return new Promise((resolve,reject)=> {
            api.http('/MedicationReminder/commonlyUsedDrugs', 'POST', false, {
            }, function (res) {
              if(res.code == 200) {
                  that.setData({
                    commonlyUsedDrugs: res.data
                  })
              }
              resolve(true)
            })
        })
    },
    // 获取用药天数
    medicationDays() {
        var that = this
        return new Promise((resolve,reject)=> {
            api.http('/MedicationReminder/medicationDays', 'POST', false, {
            }, function (res) {
            if(res.code == 200) {
                that.setData({
                    arr: res.data
                })
            }
            resolve(true)
            })
        })
    },
    // 获取每次用量
    dosage() {
        var that = this
        return new Promise((resolve,reject)=> {
            api.http('/MedicationReminder/dosage', 'POST', false, {
            }, function (res) {
                if(res.code == 200) {
                    if (res.data.dosage.length!=0&&res.data.unit.length!=0) {
                        var arr = []
                        arr.push(res.data.dosage)
                        arr.push(res.data.unit)
                        that.setData({
                            dosagearr: arr
                        })
                    }
                }
                resolve(true)
            })
        })
    },
    // 获取用药分类
    drugCategory() {
        var that = this
        return new Promise((resolve,reject)=> {
            api.http('/MedicationReminder/drugCategory', 'POST', false, {
            }, function (res) {
                if(res.code == 200) {
                    that.setData({
                        type: res.data
                    }, () => {
                        if (that.data.type.length>0) {
                            that.drugs(that.data.type[0].id)
                        }
                    })
                }
                resolve(true)
            })
        })
    },
    // 获取药品
    drugs(e) {
        var that = this,type=false
        var category_id = ''
        if (typeof(e)!='undefined') {
            category_id = e
        } else {
            if (this.data.plactive !== '') {
                category_id = this.data.type[this.data.plactive].id
            } else {
                type = true
            }
        }
        api.http('/MedicationReminder/drugs', 'POST', type, {
            category_id,
            search: this.data.inpval
        }, function (res) {
          if(res.code == 200) {
            if(that.data.inpval=='') {
                that.setData({
                    rtype: res.data
                })
            } else {
                that.setData({
                    sousuolist: res.data
                }) 
            }
          }
        })
    },
    
    // 滚动-选择药品名称
    smedication(e) {
        var that = this
        this.setData({
            active: e.currentTarget.dataset.index,
            activeid: that.data.commonlyUsedDrugs[e.currentTarget.dataset.index].id,
            plactiveid: 0
        })
    },
    // 打开遮罩
    showselect() {
        var that = this
        this.setData({
         select: !that.data.select
        })
    },
    // 选中遮罩左侧type
    plactivefun(e) {
        var that = this
        this.setData({
            plactive: e.currentTarget.dataset.index,
        }, () => {
            that.drugs()
        })
    },
    // 叉号关闭
    gbfun() {
        this.setData({
            inpval: '',
            oldval: '',
            search: '',
            showall: true
        })
    },
    // 离开遮罩触发
    afterleave() {
        var that = this
        this.setData({
            select: false,
            showall: true,
            inpval: '',
            oldval: ''
        })
    },
    inputHandler(e) {
        this.setData({
            oldval: e.detail.value
        })
    },
    // 输入框回车触发
    confirmTap() {
        var that = this
        this.setData({
            plactive: '',
            inpval: that.data.oldval,
            showall: false
        }, () => {
            that.drugs()
        })
    },
    // 确定
    yyp(e) {
        var that = this,arrlist=[]
        if(this.data.inpval=='') {
            arrlist = this.data.rtype
            this.setData({
                plactiveid: that.data.type[that.data.plactive].id
            })
        } else {
            arrlist = this.data.sousuolist
            this.setData({
                plactiveid: that.data.sousuolist[e.currentTarget.dataset.index].category_id
            })
        }
        var num = 0
        for (let index = 0; index < this.data.commonlyUsedDrugs.length; index++) {
            if (arrlist[e.currentTarget.dataset.index].id == this.data.commonlyUsedDrugs[index].id) {
                this.setData({
                    showscid: true,
                    scid: 'scid'+this.data.commonlyUsedDrugs[index].id,
                    active: index,
                    activeid: arrlist[e.currentTarget.dataset.index].id,
                    showscidname: '',
                })
                
            } else {
                num = num + 1
            }
        }
        if (num==this.data.commonlyUsedDrugs.length) {
            this.setData({
                showscid: false,
                scid: '',
                active: null,
                activeid: arrlist[e.currentTarget.dataset.index].id,
                showscidname: arrlist[e.currentTarget.dataset.index].name
            })
        }
        this.setData({
            select: false,
            showall: true,
            inpval: '',
            oldval: ''
        })
    },
    // 选择用药开始时间
    getDateTime(e) {
        this.setData({
            'obj.data': e.detail.value
        }, () => {
            this.watchstr()
        })
    },
    // 用药天数
    arrChange(e) {
        var that = this
        this.setData({
            'obj.days': that.data.arr[e.detail.value].title,
            daysindex: e.detail.value
        }, () => {})
    },
    // 用药频率
    frequencyarrChange(e) {
        var that = this
        if(this.data.frequencyindex!=e.detail.value) {
            this.setData({
                showbtm: false,
                time: ['']
            })
        }
        this.setData({
            zlist: [{title:'周一',type: false},{title:'周二',type: false},{title:'周三',type: false},{title:'周四',type: false},{title:'周五',type: false},{title:'周六',type: false},{title:'周日',type: false}],
            'obj.frequency': that.data.frequencyarr[e.detail.value].title,
            frequencyindex: e.detail.value,
            ylist: JSON.parse(JSON.stringify(that.data.json))
        }, () => {
            this.watchstr()
        })
    },
    // 周
    zboxfun(e) {
        var str = "zlist[" + e.currentTarget.dataset.index + "].type",that=this
        this.setData({
            [str]: !that.data.zlist[e.currentTarget.dataset.index].type
        }, () => {
            this.watchstr()
        })
    },
    // 月
    yboxfun(e) {
        var str = "ylist[" + e.currentTarget.dataset.index + "].type",that=this
        this.setData({
            [str]: !that.data.ylist[e.currentTarget.dataset.index].type
        }, () => {
            this.watchstr()
        })  
    },
    // 用药次数
    numberarrChange(e) {
        var that = this
        var obj = '',arr=[]
        for (let index = 1; index <= that.data.numberarr[e.detail.value].id; index++) {
            arr.push(obj)
        }
        this.setData({
            'obj.number': that.data.numberarr[e.detail.value].title,
            numberindex: that.data.numberarr[e.detail.value].id,
            time: arr,
            showbtm: false
        }, () => {
            this.watchstr()
        })
    },
    // 每次用量确认触发
    bindMultiPickerChange: function (e) {
        var that = this
        this.setData({
            'obj.dosage': that.data.dosagearr[0][e.detail.value[0]]+that.data.dosagearr[1][e.detail.value[1]],
            dosageindex: e.detail.value
        })
      },
    // 每次用量修改列触发
    bindMultiPickerColumnChange: function (e) {
    // console.log('修改的列为', e.detail.column, '，值为', e.detail.value);
    },
    // 用药时间选择
    getmoretime(e) {
        var str = "time[" + e.currentTarget.dataset.num + "]"
        this.setData({
            [str]: e.detail.value
        }, () => {
            this.watchstr()
        })
    },
    // 开启提醒
    kqtxfun() {
        var that = this
        var day_id = this.data.arr[this.data.daysindex].id
        var company = ''
        var days = []
        if (this.data.frequencyindex == 0) {
            company = 'day'
        } else if (this.data.frequencyindex == 1) {
            company = 'week'
            for (let index = 1; index <= this.data.zlist.length; index++) {
                if (this.data.zlist[index-1].type == true) {
                    days.push(index)
                }
            }
        } else if (this.data.frequencyindex == 2) {
            company = 'month'
            for (let index = 1; index <= this.data.ylist.length; index++) {
                if (this.data.ylist[index-1].type == true) {
                    days.push(index)
                }
            }
        }
        var url = ''
        if (typeof(this.data.options.reminder_id)=='undefined') {
            url = '/MedicationReminder/addReminder' // 添加
        } else {
            url = '/MedicationReminder/editReminder' // 编辑
        }
        api.http(url, 'POST', true, {
            drugs_id: this.data.activeid,
            start_date: this.data.obj.data,
            day_id,
            company,
            days: days.toString(),
            consumption: this.data.obj.dosage,
            usage_time: this.data.time.toString(),
            reminder_id: this.data.reminder_id,
            category_id: this.data.plactiveid
        }, function (res) {
          if(res.code == 200) {
            if (typeof(that.data.options.reminder_id)=='undefined') {
                wx.showToast({
                    title: res.msg,
                    icon: 'success',
                    duration: 1000
                })
                // 订阅消息
                // that.getSetting()
            } else {
                wx.showToast({
                    title: '修改成功',
                    icon: 'success',
                    duration: 1000
                })
                // 订阅消息
                // that.getSetting()
            }
            setTimeout(() => {
                wx.navigateBack({
                    delta: 1
                })
            }, 1000);
          } else {
            wx.showToast({
                title: res.msg,
                icon: 'none',
                duration: 1000
            }) 
          }
        })
    },
    // 订阅消息
    getSetting() {
        var that = this
        api.http('/MedicationReminder/medicationDays', 'POST', false, {
        }, function (res) {
            if(res.code == 200) {
                // wx.requestSubscribeMessage({
                //     tmplIds: [tmplIds],
                //     success (res) { 
                //       console.log('订阅消息 成功 ');
                //       console.log(res);
                //     },
                //     fail (er){
                //       console.log("订阅消息 失败 ");
                //       console.log(er);
                //     },
                //     complete (){
                //         setTimeout(() => {
                //             wx.navigateBack({
                //                 delta: 1
                //             })
                //         }, 1000);
                //     }
                // })
            }
        })

        // wx.getSetting({
        //   withSubscriptions: true,   //  这里设置为true,下面才会返回mainSwitch
        //   success: function(res){   
        //     // 调起授权界面弹窗
        //     console.log(res.subscriptionsSetting.mainSwitch)
        //     if (res.subscriptionsSetting.mainSwitch) {  // 用户打开了订阅消息总开关
        //       if (res.subscriptionsSetting.itemSettings != null) {   // 用户同意总是保持是否推送消息的选择, 这里表示以后不会再拉起推送消息的授权
        //         let moIdState = res.subscriptionsSetting.itemSettings[tmplIds];  // 用户同意的消息模板id
        //         if(moIdState === 'accept'){   
        //           console.log('接受了消息推送');
    
        //         }else if(moIdState === 'reject'){
        //           console.log("拒绝消息推送");
    
        //         }else if(moIdState === 'ban'){
        //           console.log("已被后台封禁");
    
        //         }
        //       } else {
        //         // 当用户没有点击 总是保持以上选择，不再询问按钮。那每次执到这都会拉起授权弹窗
        //         wx.showModal({
        //           title: '提示',
        //           content:'请授权开通服务通知',
        //           showCancel: true,
        //           success: function (ress) {
        //             if (ress.confirm) {  
        //               wx.requestSubscribeMessage({   // 调起消息订阅界面
        //                 tmplIds: [tmplIds],
        //                 success (res) { 
        //                   console.log('订阅消息 成功 ');
        //                   console.log(res);
        //                 },
        //                 fail (er){
        //                   console.log("订阅消息 失败 ");
        //                   console.log(er);
        //                 }
        //               })     
                            
        //             }
        //           }
        //         })
        //       }
        //     } else {
        //         // 没有开启订阅消息的权限
        //     }      
        //   },
        //   fail: function(error) {
        //     console.log(error);
        //   },
        // })
    },
    // 监听底部(修改页面内容触发)
    watchstr() {
        if(this.data.frequencyindex==0) {
            var ztype = 0
            for (let index = 0; index < this.data.time.length; index++) {
                if (this.data.time[index]!='') {
                    ztype = ztype + 1
                }
            }
            if(this.data.obj.data!=''&&this.data.numberindex!==0&&ztype==this.data.time.length) {
                this.setData({
                    showbtm: true
                })
            } else {
                this.setData({
                    showbtm: false
                })
            }
            // 获取底部按钮容器的高度
            this.funbtnhei()
        }
        if(this.data.frequencyindex==1) {
            this.setData({
                numberindex: 1
            }, () => {
                var ztype = false
                for (let index = 0; index < this.data.zlist.length; index++) {
                    if (this.data.zlist[index].type==true) {
                        ztype = true
                    }
                }
                if(this.data.obj.data!=''&&this.data.numberindex!==0&&this.data.time[0]!=''&&ztype==true) {
                    this.setData({
                        showbtm: true
                    })
                } else {
                    this.setData({
                        showbtm: false
                    })
                }
                // 获取底部按钮容器的高度
                this.funbtnhei()
            })
        }
        if(this.data.frequencyindex==2) {
            var arr = ['']
            if(this.data.time.length>0) {
                if (this.data.time[0]!='') {arr=this.data.time} 
            }
            this.setData({
                time: arr,
                numberindex: 1
            }, () => {
                var ztype = false
                for (let index = 0; index < this.data.ylist.length; index++) {
                    if (this.data.ylist[index].type==true) {
                        ztype = true
                    }
                }
                if(this.data.obj.data!=''&&this.data.numberindex!==0&&this.data.time[0]!=''&&ztype==true) {
                    this.setData({
                        showbtm: true
                    })
                } else {
                    this.setData({
                        showbtm: false
                    })
                }
                // 获取底部按钮容器的高度
                this.funbtnhei()
            })
        }
        
    },
    // 获取底部按钮容器的高度
    funbtnhei() {
        var  that = this
        const query = wx.createSelectorQuery()
        query.select('.btm').boundingClientRect((result) => {
            that.setData({
                btmh: result.height
            })
        }).exec()
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: async function(options) {
        var title = ''
        // 编辑页面传参
        if (typeof(options.reminder_id)!='undefined') {
            this.setData({
                title: 0, // 底部按钮类型
                showscid: false // 是否展示滚动scroll
            })
            title = '编辑用药提醒'
        } else {
            this.setData({
                title: 1 // 底部按钮类型
            })
            title = '添加用药提醒'
        }
        wx.setNavigationBarTitle({
            title
        })

        // 月份数组
        var arr = []
        for (let index = 1; index <= 30; index++) {
            if (index<10) {
                index = '0'+index
            }
            var obj = {title: index,type: false}
            arr.push(obj)
        }
        this.setData({
            ylist: arr,
            json: JSON.parse(JSON.stringify(arr))
        })
 
        // 同步调取接口 *防止编辑回显过程报错

        if(typeof(options.reminder_id)!='undefined') {
            wx.showLoading({
                title: '加载中...',
                mask: true
            })
        }

        // 获取药品
        await this.commonlyUsedDrugs()
        // 获取用药天数
        await this.medicationDays()
        // 获取每次用量
        await this.dosage()
        // 获取药品分类
        await this.drugCategory()

        // 编辑页面传参
        if (typeof(options.reminder_id)!='undefined') {
            this.setData({
                options: options,
            })
            await this.reminderDetails()
        } else {
            // 获取底部按钮容器的高度
            this.funbtnhei()
        }
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    // onShareAppMessage() {

    // }
})